package com.hyperfix.washer.websocket;

import com.hyperfix.models.washer.pojos.Monitor;
import com.hyperfix.washer.common.MonitorRegistrar;
import com.hyperfix.washer.common.StatusRegistrar;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.io.IOException;

/**
 * @author JiangChunYu
 * 2024/4/20
 */
@Slf4j
@Component
public class MessageSender {
    @Resource
    private MonitorRegistrar monitorRegistrar;
    @Resource
    private StatusRegistrar statusRegistrar;

    public void sendCurrentUsers(Integer pipelineId, Object data) {
        for (Monitor monitor : monitorRegistrar.getAllMonitor()) {
            if (monitor.getPipelineId().equals(pipelineId)) {
                Session session = monitor.getSession();
                if (session.isOpen()) {
                    try {
                        session.getBasicRemote().sendObject(data);
                    } catch (IOException | EncodeException e) {
                        log.error(e.getMessage());
                    }
                }
            }
        }
    }

    public void sendStatus(Object data) {
        for (Session session : statusRegistrar.getAllSession()) {
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendObject(data);
                } catch (IOException | EncodeException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}
